<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <script type="text/javascript">
      // 后端返回直接执行的方法，相当于执行这个方法，由于后端把返回的数据放在方法的参数里，所以这里能拿到res。
      window.jsonpCb = function (res) {
        console.log(res);
      };
    </script>
    <script
      src="http://localhost:9871/api/jsonp?msg=helloJsonp&cb=jsonpCb"
      type="text/javascript"
    ></script>

    <script>
      function jsonp(obj) {
        return new Promise((resolve, reject) => {
          const script = document.createElement("script");
          let dataString = obj.url.indexOf("?") == -1 ? "?" : "&";
          for (let i in obj.data) {
            dataString += i + "=" + obj.data + "&";
          }

          const jsonp = "json_cd" + Math.random().toString().replace(".", "");
          script.src = obj.url + dataString + "callback=" + jsonp;
          document.body.appendChild(script);
          window[jsonp] = (data) => {
            document.body.removeChild(script);
            resolve(data);
          };
        });
      }

      jsonp({
        url: "http://localhost:3001/push",
        data: {
          name: "dz",
          age: "26",
        },
      }).then((data) => {
        console.log(data);
      });
    </script>
  </body>
</html>
